package com.scc.service.impl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.scc.mapper.AdminMapper;
import com.scc.pojo.*;
import com.scc.service.AdminService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    //注入mapper层的接口，连接dao层
    @Autowired
    private AdminMapper adminMapper;

    //管理员登录的查询数据库表的逻辑方法
    @Override
    public Admin select(Admin admin) {
        //往adminMapper传入对象进行查找
        return adminMapper.select(admin);
    }


    //管理员添加员工数据的方法
    @Override
    public void addEmp(Emp emp) {
        //将对象传入mapper接口
        adminMapper.addEmp(emp);
    }


    //员工信息表的分页查询和展示
    public PageBean pageSearch(Integer page, Integer pageSize, String name, Integer gender, String account, LocalDate beginTime, LocalDate endTime) {
        //设置分页参数
        PageHelper.startPage(page, pageSize);
        //连接dao层进行查询数据库操作 返回值为Emp对象
        List<Emp> empList = adminMapper.page(name,gender,account,beginTime,endTime);
        //储存查询信息
        PageInfo<Emp> pageInfo = new PageInfo<>(empList);
        //返回查询分页信息
        return new PageBean(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public void delete(Integer id) {
        //连接dao层，传入id删除数据
        adminMapper.delete(id);
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        //传入数据到dao层
        adminMapper.deleteByIds(ids);
    }

    @Override
    public void updatePassword(Admin admin) {
        //传入一个新的管理员对象
        adminMapper.updatePassword(admin);
    }

    @Override
    public Emp getEmpMessage(Integer id) {
        //传入id获取一个用户的对象
        return adminMapper.getEmpMessageById(id);
    }

    //修改用户信息的方法
    @Override
    public void modifyEmp(Emp emp) {
        //无需返回值 //传入要修改的值(id、name、gender、image、account、password、salary、lastOperationTime)
        adminMapper.modify(emp.getId(),emp.getName(),emp.getGender(),emp.getImage()
                ,emp.getAccount(),emp.getPassword(),emp.getSalary()
                ,emp.getLastOperationTime());
    }

    /// 添加考勤日期的操作
    //获得所有用户的信息
    @Override
    public void getAllEmpMessage(String attendanceName, LocalDate attendanceDate, LocalDateTime endAttendanceTime) {
        //获取一个员工对象集合
        List<Emp> empMessage = adminMapper.getAllEmpMessage();
        //获取一个考勤对象的集合
        List<Attendance> attendances = new ArrayList<>();
        //获取对象
        Attendance attendance ;
        //遍历集合获取信息
        for (Emp emp : empMessage) {
            //每次创建一个新的对象
            attendance = new Attendance();
            //添加数据
            attendance.setId(emp.getId());///员工id
            attendance.setName(emp.getName());///员工姓名
            attendance.setGender(emp.getGender());///员工性别
            attendance.setAccount(emp.getAccount());///员工账号
            attendance.setDeductSalary(emp.getDeductSalary());///已扣工资
            attendance.setAttendanceName(attendanceName);///考勤名称
            attendance.setAttendanceDate(attendanceDate);///考勤日期
            attendance.setEndAttendanceTime(endAttendanceTime);///考勤截止时间
            //添加对象
            attendances.add(attendance);
        }
        //将考勤数据添加进入考勤表
        //遍历集合获得每一个考勤对象，将对象传入数据处理层
        //将对象传给dao层 通过遍历集合获取对象传入dao层
        for (Attendance newAttendance : attendances) adminMapper.addAttendance(newAttendance);
    }
    //考勤表信息的获取
    @Override
    public PageBean getAllAttendance(Integer page, Integer pageSize, String name, Integer gender, String account, Integer empAttendanceStatus, LocalDate attendanceDate) {
        //设置分页参数
        PageHelper.startPage(page, pageSize);
        //连接数据层获取数据
        List<Attendance> attendanceList = adminMapper.getAllAttendance(name,gender,account,empAttendanceStatus,attendanceDate);
        //转化为分页集合
        PageInfo<Attendance> pageInfo = new PageInfo<>(attendanceList);
        //返回分页对象
        return new PageBean(pageInfo.getTotal(), pageInfo.getList());
    }
    //根据id删除考勤表数据
    @Override
    public void deleteAttendanceByIds(List<Integer> ids) {
        //数据传到dao层
        adminMapper.deleteAttendanceByIds(ids);
    }
    //根据id扣除工资
    @Override
    public void deductSalary(String deductMessage) throws JsonProcessingException {
        //前端传递的是一个json解析并获得ids和money
        //引入jackson库的objectMapper进行解析
        ObjectMapper objectMapper = new ObjectMapper();
        //JsonNode
        JsonNode jsonNode = objectMapper.readTree(deductMessage);
        // 从JSON节点中获取ids和//无需返回值
        // adminMapper.money字段的值
        String idsString = jsonNode.get("ids").asText();//获取前端ids数组
        Integer money = jsonNode.get("money").asInt();//获取money
        //将idsString转化为集合
        List<Integer> ids = new ArrayList<>();
        String[] idsArray = idsString.split(",");
        //遍历添加进入集合
        for (String string : idsArray) {
            ids.add(Integer.parseInt(string));
        }
        //考勤表扣完工资之后
        adminMapper.deductSalary(ids,money);
        ///逻辑外键
        ///员工表的工资也要扣除，并且要在扣除工资行中加上扣除的金额
        //根据数据找到扣除员工表的员工的id 返回一个考勤对象
        //循环从考勤表获得员工数据,每次传一个id
        for (Integer id : ids) {
            Attendance attendance = adminMapper.getAttendanceById(id);
            //员工账号唯一用员工账号为条件，找到对应的员工进行操作，获得考勤对象中用户的账号
            //无需返回值（传入账号，扣除的金额大小）
            adminMapper.modifyEmpByAccount(attendance.getAccount(),money);

        }
    }
    //员工请假信息的获取或者查询
    @Override
    public PageBean getEmpLeaveMsg(Integer page, Integer pageSize, String name, Integer gender, String account, LocalDate startDate, LocalDate endDate) {
        //设置分页参数
        PageHelper.startPage(page, pageSize);
        //传入员工姓名，性别，账号，开始时间，结束时间给dao层，返回一个员工请假对象的集合
        List<Leave> getEmpLeaveMsg = adminMapper.getEmpLeaveMsg(name,gender,account,startDate,endDate);
        PageInfo<Leave> pageInfo = new PageInfo<>(getEmpLeaveMsg);
        //返回对象
        return new PageBean(pageInfo.getTotal(), pageInfo.getList());
    }
    //跟据id来操作用户审批状态
    @Override
    public void modifyEmpLeaveApproveStatus(String approveStatusMsg) throws JsonProcessingException {
        //引入jackSON库的核心工具对象
        ObjectMapper objectMapper = new ObjectMapper();
        //提取json的节点（逗号分割开每一个部分）
        JsonNode jsonNode = objectMapper.readTree(approveStatusMsg);
        //获取json数据
        //用户的id
        String idsString = jsonNode.get("ids").asText();
        //请假审批的状态
        int approveStatus = jsonNode.get("approveStatus").asInt();
        //将idsString转化为集合
        List<Integer> ids = new ArrayList<>();
        String[] idsArray = idsString.split(",");
        for (String string : idsArray) {
            ids.add(Integer.parseInt(string));
        }
        //修改请假表
        adminMapper.modifyEmpLeaveApproveStatus(ids,approveStatus);
        /*
         *审批通过，考勤表的状态要变成请假
         *审批不通过考勤状态不变
         *判断
         */
        if(approveStatus==1){
            /*
            管理员通过
            根据通过请假审批的id来请假表获取员工的专属账号,返回员工账号的集合,员工请假表搜索
            */
            List<String> account =  adminMapper.getEmpAccountByIds(ids);
            //根据员工账号修改员工考勤表的考勤状态->修改为请假
            adminMapper.modifyEmpAttendanceStatus(account);
        }
    }

    /// 员工离职系列操作
    //获取员工离职对象或者查询离职对象
    @Override
    public PageBean getEmpResignMsg(Integer page, Integer pageSize, String name, Integer gender, String account, LocalDate startDate, LocalDate endDate) {
        //设置分页数据
        PageHelper.startPage(page, pageSize);
        //获取员工离职信息对象的集合
        List<Resign> resignMsgList = adminMapper.getEmpResignMsg(name,gender,account,startDate,endDate);
        //PageInfo集合
        PageInfo<Resign> pageInfo = new PageInfo<>(resignMsgList);
        //返回一个PageInfo对象
        return new PageBean(pageInfo.getTotal(), pageInfo.getList());
    }

    //管理员审批员工离职申请的操作
    @Override
    public void modifyEmpResignApproveStatus(String resignApproveStatus) throws JsonProcessingException {
        //解析json格式
        ObjectMapper objectMapper = new ObjectMapper();
        //获取节点分割器
        JsonNode jsonNode = objectMapper.readTree(resignApproveStatus);
        //获取id字符串
        String idsString = jsonNode.get("ids").asText();
        //获取审批的结果
        int resignStatus = jsonNode.get("approveStatus").asInt();
        //idsString转化为集合
        List<Integer> ids = new ArrayList<>();
        String[] idsArray = idsString.split(",");
        //遍历数组添加进入集合
        for (String string : idsArray) {
            ids.add(Integer.parseInt(string));
        }
        ///如果审批通过要获取当前日期为离职时间，反之不需要加入离职时间
        //获取离职时间
        LocalDate resignDate = null;
        if(resignStatus == 1){
            LocalDateTime resignTime = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            resignDate = LocalDate.parse(resignTime.format(formatter), formatter);
        }
        //传入数据给数据库
        adminMapper.modifyEmpResignApproveStatus(ids,resignStatus,resignDate);
    }

    /// 管理员对团建活动的系列操作
    //获得团建活动信息数据
    @Override
    public PageBean getTeamBuildingActivitiesMsg(Integer page, Integer pageSize, String teamBuildingName, Integer activityStatus, LocalDateTime begin, LocalDateTime end) {
        //分页参数
        PageHelper.startPage(page, pageSize);
        //返回一个团建活动对象的集合
        List<TeamBuildingActivities> teamBuildingActivitiesList = adminMapper.getTeamBuildingActivitiesMsg(teamBuildingName,activityStatus,begin,end);
        PageInfo<TeamBuildingActivities> pageInfo = new PageInfo<>(teamBuildingActivitiesList);
        return new PageBean(pageInfo.getTotal(), pageInfo.getList());
    }

    //添加团建活动
    @Override
    public void addTeamBuildingActivities(TeamBuildingActivities teamBuildingActivities) {
        //无需返回值
        adminMapper.addTeamBuildingActivities(teamBuildingActivities);
    }

    //删除团建活动
    @Override
    public void deleteTeamBuildingActivities(List<Integer> ids) {
        //删除无需返回值
        adminMapper.deleteTeamBuildingActivities(ids);
        //删除一个团建活动，员工报名团建活动表的数据也要删除
        adminMapper.deleteEmpTeamBuildingActivities(ids);
    }

    //根据id获取团建活动的信息
    @Override
    public TeamBuildingActivities getTeamBuildingActivitiesMsgById(Integer id) {
        //返回一个团建活动的对象
        return adminMapper.getTeamBuildingActivitiesMsgById(id);
    }

    //修改团建活动的信息
    @SneakyThrows
    @Override
    public void modifyTeamBuildingActivities(String tbaMsg) {
        //解析json
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(tbaMsg);
        Integer id = jsonNode.get("id").asInt();
        String teamBuildingName = jsonNode.get("teamBuildingName").asText();
        Integer maxCapacity = jsonNode.get("maxCapacity").asInt();
        ///将时间字符串转化为时间对象
        String StartTime = jsonNode.get("startTime").asText();
        String EndTime = jsonNode.get("endTime").asText();
        LocalDateTime startTime = LocalDateTime.parse(StartTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime endTime = LocalDateTime.parse(EndTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Integer activityStatus = jsonNode.get("activityStatus").asInt();
        //修改团建活动信息表
        adminMapper.modifyTeamBuildingActivities(id,teamBuildingName,maxCapacity,startTime,endTime,activityStatus);
        //修改员工报名团建活动信息
        adminMapper.modifyEmpTeamBuildingActivities(id,teamBuildingName);
    }

    //获取单个员工活动报名的信息
    @Override
    public PageBean geEmpTeamBuildingActivitiesMsg(Integer id, Integer page, Integer pageSize, String name, Integer gender, String account, String activityDuration, LocalDateTime begin, LocalDateTime end, Integer empActivityStatus) {
        //分页参数
        PageHelper.startPage(page, pageSize);
        //返回一个员工团建活动报名对象的集合
        List<EmpTeamBuildingActivityRegistration> EmpTBAR = adminMapper.geEmpTeamBuildingActivitiesMsg(id,name,gender,account,activityDuration,begin,end,empActivityStatus);
        //pageinfo集合
        PageInfo<EmpTeamBuildingActivityRegistration> pageInfo = new PageInfo<>(EmpTBAR);
        return new PageBean(pageInfo.getTotal(), pageInfo.getList());
    }

    //员工团建活动报名表的删除操作
    @Override
    public void deleteEmpTeamBuildingActivities(List<String> account) {
        adminMapper.deleteEmpTeamBuildingActivitiesByAccounts(account);
    }

    //培训活动信息表的获取和查询
    @Override
    public PageBean getTrainingActivities(Integer page, Integer pageSize, String trainingName, Integer activityStatus, LocalDate startTime, LocalDate endTime) {
        //分页参数
        PageHelper.startPage(page, pageSize);
        //返回一个培训活动对象的集合
        List<TrainingActivity> trainingActivityList = adminMapper.getTrainingActivities(trainingName,activityStatus,startTime,endTime);
        PageInfo<TrainingActivity> pageInfo = new PageInfo<>(trainingActivityList);
        return new PageBean(pageInfo.getTotal(), pageInfo.getList());
    }

    //培训活动信息表的删除
    @Override
    public void deleteTrainingActivityByIds(List<Integer> ids) {
        //培训活动信息表删除
        adminMapper.deleteTrainingActivityByIds(ids);
        //培训活动员工活动报名表也要删除
        adminMapper.deleteEmpTrainingActivityByIds(ids);
    }

    //根据id获取员工信息
    @Override
    public TrainingActivity getTrainingActivityMsgById(Integer id) {
        return adminMapper.getTrainingActivityMsgById(id);
    }

    //添加培训活动
    @Override
    public void addTrainingActivity(TrainingActivity trainingActivity) {
        adminMapper.addTrainingActivity(trainingActivity);
    }

    //修改培训活动
    @Override
    public void modifyTrainingActivity(TrainingActivity trainingActivity) {
        adminMapper.modifyTrainingActivity(trainingActivity);
    }

    //查询或者获取某一个培训活动的员工报名表
    @Override
    public PageBean getEmpTrainingActivity(Integer page, Integer pageSize, Integer id, String name, Integer gender, String account, LocalDateTime startTime, LocalDateTime endTime, Integer activityStatus, String activityDuration, Integer activityScore) {
        //分页参数
        PageHelper.startPage(page, pageSize);
        //查询员工培训活动报名表返回一个员工培训活动对象的集合
        List<EmpTrainingActivity> empTrainingActivityList = adminMapper.getEmpTrainingActivity(id,name,gender,account,startTime,endTime,activityStatus,activityDuration,activityScore);
        PageInfo<EmpTrainingActivity> pageInfo = new PageInfo<>(empTrainingActivityList);
        return new PageBean(pageInfo.getTotal(), pageInfo.getList());
    }

    //管理员根据员工账号删除员工培训报名表员工的信息
    @Override
    public void deleteEmpTrainingActivityByAccounts(List<String> accounts) {
        adminMapper.deleteEmpTrainingActivityByAccounts(accounts);
    }

    //管理员对于参加培训活动的员工进行打分操作
    @SneakyThrows
    @Override
    public void modifyEmpTrainingActivityScore(String scoreMsg, String account) {
        //解析json获取信息
        ObjectMapper objectMapper = new ObjectMapper();
        //获取节点解析器
        JsonNode jsonNode = objectMapper.readTree(scoreMsg);
        //获取json中的信息
        Integer activityScore = jsonNode.get("activityScore").asInt();
        Integer changeScore = jsonNode.get("changeScore").asInt();
        //要对培训活动员工报名表进行修改分数
        adminMapper.modifyEmpTrainingActivityScore(activityScore,account);
        //要对员工总表进行加分
        adminMapper.modifyEmpTrainingScore(changeScore,account);
    }

    //获取员工培训分数操作
    @Override
    public Integer getEmpTrainingActivityScoreByAccount(String account, Integer id) {
        //获取员工培训分数根据账号和id
        return adminMapper.getEmpTrainingActivityScoreByAccount(account,id);
    }

    //管理员结算员工工资
    @SneakyThrows
    @Override
    public void addEmpSalary(String empSalaryMsg) {
        //解析json
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(empSalaryMsg);
        //解析完成后用员工工资对象装载
        int id = jsonNode.get("id").asInt();
        String account = jsonNode.get("account").asText();
        LocalDate salaryDate = LocalDate.parse(jsonNode.get("salaryDate").asText(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        int deductSalary = jsonNode.get("deductSalary").asInt();
        int salary = jsonNode.get("salary").asInt();
        //新建一个对象
        EmpSalary empSalary = new EmpSalary(id,account,salaryDate,deductSalary,salary);
        adminMapper.insertEmpSalary(empSalary);
        /*
        员工工资结算完成之后要对员工工资进行初始化，扣除工资清零,员工工资要回到原来的样子
        原来的工资是结算工资加上已扣工资
        */
        int oldSalary = salary+deductSalary;
        adminMapper.initializationSalary(id,account,oldSalary);
    }

    //管理员批量结算员工工资操作
    @Override
    public void addEmpSalaryByIds(List<Integer> ids, LocalDate salaryDate) {
        //根据id获取相应员工的信息，返回一个集合
        List<Emp> getEmpMsgByIds = adminMapper.getEmpMsgByIds(ids);
        //遍历集合获取员工的id,account,deductSalary,salary
        for (Emp emp : getEmpMsgByIds) {
            //每次都创建一个新的员工工资对象
            EmpSalary empSalary = new EmpSalary(emp.getId(),emp.getAccount(),salaryDate,emp.getDeductSalary(),emp.getSalary());
            //添加员工工资表的操作
            adminMapper.insertEmpSalary(empSalary);
            //结算完成之后要对该员工的工资进行初始化
            int oldSalary = emp.getSalary()+emp.getDeductSalary();
            //初始化操作
            adminMapper.initializationSalary(emp.getId(),emp.getAccount(),oldSalary);
        }
    }

    ///获取管理员账号
    @Override
    public void getAdminMsg(String account) {
        adminMapper.selectAdminMsg(account);
    }

    //获取员工在线信息表的信息
    @Override
    public PageBean getEmpOnlineMsg(Integer page, Integer pageSize, String name, String account, LocalDate start, LocalDate end) {
        PageHelper.startPage(page, pageSize);
        List<EmpOnLine> empOnLineList = adminMapper.selectEmpOnlineMsg(name,account,start,end);
        PageInfo<EmpOnLine> pageInfo = new PageInfo<>(empOnLineList);
        return new PageBean(pageInfo.getTotal(), pageInfo.getList());
    }

    //管理员根据id删除员工在线信息表的信息
    @Override
    public void deleteEmpOnlineMsgByIds(List<Integer> ids) {
        adminMapper.deleteEmpOnlineMsgByIds(ids);
    }
}
